package com.unity.bh3.service.impl;

import com.unity.bh3.dto.UserInfoResponse;
import com.unity.bh3.dto.UserLoginRequest;
import com.unity.bh3.dto.UserRegisterRequest;
import com.unity.bh3.entity.User;
import com.unity.bh3.mapper.UserMapper;
import com.unity.bh3.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserInfoResponse register(UserRegisterRequest request) {
        // 检查用户名是否已存在
        User existUser = userMapper.findByUsername(request.getUsername());
        if (existUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword()); // 实际应用中应该加密密码
        user.setNickname(request.getNickname());
        user.setExp(0);
        user.setDiamond(100); // 初始赠送100钻石
        user.setGold(1000);   // 初始赠送1000金币
        user.setStamina(120); // 初始体力120
        user.setDisplayCharacterId(1L); // 默认看板角色ID

        // 保存用户
        userMapper.insert(user);

        // 返回用户信息
        return convertToUserInfoResponse(user);
    }

    @Override
    public UserInfoResponse login(UserLoginRequest request) {
        // 根据用户名查询用户
        User user = userMapper.findByUsername(request.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码
        if (!user.getPassword().equals(request.getPassword())) { // 实际应用中应该比较加密后的密码
            throw new RuntimeException("密码错误");
        }

        // 返回用户信息
        return convertToUserInfoResponse(user);
    }

    @Override
    public UserInfoResponse getUserInfo(Long userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return convertToUserInfoResponse(user);
    }

    @Override
    public boolean addDiamond(Long userId, Integer amount) {
        if (amount <= 0) {
            throw new RuntimeException("增加的钻石数量必须大于0");
        }
        
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        user.setDiamond(user.getDiamond() + amount);
        return userMapper.updateDiamond(user) > 0;
    }

    @Override
    public boolean reduceDiamond(Long userId, Integer amount) {
        if (amount <= 0) {
            throw new RuntimeException("减少的钻石数量必须大于0");
        }
        
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (user.getDiamond() < amount) {
            throw new RuntimeException("钻石不足");
        }
        
        user.setDiamond(user.getDiamond() - amount);
        return userMapper.updateDiamond(user) > 0;
    }

    @Override
    public boolean addGold(Long userId, Integer amount) {
        if (amount <= 0) {
            throw new RuntimeException("增加的金币数量必须大于0");
        }
        
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        user.setGold(user.getGold() + amount);
        return userMapper.updateGold(user) > 0;
    }

    @Override
    public boolean reduceGold(Long userId, Integer amount) {
        if (amount <= 0) {
            throw new RuntimeException("减少的金币数量必须大于0");
        }
        
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (user.getGold() < amount) {
            throw new RuntimeException("金币不足");
        }
        
        user.setGold(user.getGold() - amount);
        return userMapper.updateGold(user) > 0;
    }

    @Override
    public boolean addStamina(Long userId, Integer amount) {
        if (amount <= 0) {
            throw new RuntimeException("增加的体力数量必须大于0");
        }
        
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        user.setStamina(user.getStamina() + amount);
        return userMapper.updateStamina(user) > 0;
    }

    @Override
    public boolean reduceStamina(Long userId, Integer amount) {
        if (amount <= 0) {
            throw new RuntimeException("减少的体力数量必须大于0");
        }
        
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (user.getStamina() < amount) {
            throw new RuntimeException("体力不足");
        }
        
        user.setStamina(user.getStamina() - amount);
        return userMapper.updateStamina(user) > 0;
    }

    @Override
    public List<UserInfoResponse> searchUsersByNickname(String nickname, int limit) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(User::getNickname, nickname)
                .last("LIMIT " + limit);
        
        return userMapper.selectList(wrapper).stream()
                .map(this::convertToUserInfoResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 将User实体转换为UserInfoResponse
     */
    private UserInfoResponse convertToUserInfoResponse(User user) {
        UserInfoResponse response = new UserInfoResponse();
        BeanUtils.copyProperties(user, response);
        
        // 计算等级：等级 = 当前经验/100
        if (user.getExp() != null) {
            response.setLevel(user.getExp() / 100);
        } else {
            response.setLevel(0);
        }
        
        return response;
    }
}